package com.party.pay;

/**
 * @author: zhaoyongke
 * @create: 2025-09-01 15:16
 * @description: XunayRefundService
 */
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class XunayRefundService {
    // 从配置文件读取（避免硬编码）

    //商户号
    private static String mchNo = "M1752112514";
    //应用ID
    private static String appId = "686f1d82e4b02e1c8b4b5935";
    //秘钥
    private static String mchKey = "fPqfOo0sVJ31uvWZPH3iRvnNIkJDeW0bajMWaU7lJPvXNlA2RgI4E3TA68qstVd1YXeMYqH8zTra460UItPDcVZ8Kk6iPR1AgvpBQCSqIOa9rCsGeQ1vHi35jWXRPeTe";
    //异步通知地址
    private static String refundUrl = "http://kcsm.cqzwyt.cn/kcsm/api/pay/notify";
    private static String refundApiUrl = "http://pay.hb-ga.com/api/refund/refundOrder";


    /**
     * 发起退款请求
     * @param mchOrderNo    原商户订单号（下单时的 mchOrderNo）
     * @param mchRefundNo   商户退款单号（唯一，如 "REF20240520001"）
     * @param refundAmount  退款金额（单位：分，如 100 代表 1元）
     * @param reason        退款原因
     * @return 退款响应结果
     */
    public XunayRefundResponse applyRefund(
            String mchOrderNo,
            String mchRefundNo,
            int refundAmount,
            String reason) throws IOException {

        // 1. 组装退款请求参数
        XunayRefundRequest refundRequest = new XunayRefundRequest();
        refundRequest.setMchNo(mchNo);
        refundRequest.setAppId(appId);
        refundRequest.setMchOrderNo(mchOrderNo);
        refundRequest.setMchRefundNo(mchRefundNo);
        refundRequest.setPayOrderId(null); // 可选：优先用 mchOrderNo，也可传 payOrderId
        refundRequest.setRefundAmount(refundAmount);
        refundRequest.setCurrency("cny"); // 固定人民币
        refundRequest.setRefundReason(reason);
        refundRequest.setReqTime(System.currentTimeMillis()); // 13位时间戳
        refundRequest.setVersion("1.0"); // 固定版本
        refundRequest.setSignType("MD5"); // 固定签名类型
        refundRequest.setNotifyUrl(refundUrl); // 可选：退款结果回调地址
        // 2. 生成签名
        String sign = XunaySignUtil.generateSign(refundRequest.toSignMap(), mchKey);
        refundRequest.setSign(sign);

        // 3. 发送退款请求
        // 3. 发送退款请求到正确的API地址并增加错误处理
        try {
            XunayRefundResponse refundResponse = XunayHttpUtil.postJson(
                    refundApiUrl, refundRequest, XunayRefundResponse.class);

            // 检查响应是否为null
            if (refundResponse == null) {
                throw new RuntimeException("退款请求失败：收到空响应");
            }

            // 4. 验证响应签名（防止篡改）
//            if (!XunaySignUtil.verifySign(refundResponse, mchKey)) {
//                throw new RuntimeException("退款响应签名验证失败，可能被篡改");
//            }

            // 5. 处理退款结果（根据业务需求扩展，如记录日志、更新订单状态）
            if (refundResponse.getCode() != 0) {
                throw new RuntimeException("退款申请失败：" + refundResponse.getMsg());
            }

            XunayRefundResponse.RefundData refundData = refundResponse.getData();
            if (refundData != null && refundData.getRefundState() == 2) {
                throw new RuntimeException("退款失败（上游渠道）：" + refundData.getChannelErrMsg());
            }

            return refundResponse;
        } catch (Exception e) {
            // 捕获并重新抛出更明确的异常
            if (e instanceof IOException) {
                throw new IOException("退款请求网络错误：" + e.getMessage(), e);
            } else {
                throw new RuntimeException("退款请求处理失败：" + e.getMessage(), e);
            }
        }


    }
}
